<template>
  <div class="container" style="padding: 10px">
    <el-form ref="elForm" :model="searchData" size="medium" label-width="100px">
      <el-row type="flex" class="row-bg">
        <DatePicker ref="DatePicker" @changeDateTime="changeTime"></DatePicker>
        <el-select
          style="width: 180px; margin: 0 10px"
          v-model="searchData.reportUser"
          clearable
          size="mini"
          @change="searchData.pageNum = 1"
          filterable
          placeholder="请选择员工"
        >
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          >
          </el-option>
        </el-select>
        <el-button
          v-hasPermi="['business:salary:list']"
          size="mini"
          type="primary"
          @click="getCommonList()"
          :disabled="searchDisabled"
          :loading="searchDisabled"
          v-if="activeName == '1'"
        >
          明细查询
        </el-button>
        <el-button
          v-hasPermi="['business:salary:listAll']"
          size="mini"
          style="margin-left: 10px"
          type="primary"
          @click="getCommonList()"
          v-if="activeName == '2'"
          :disabled="allSearchDis"
          :loading="allSearchDis"
        >
          汇总查询
        </el-button>
        <el-button
          v-hasPermi="['business:salary:export']"
          size="mini"
          type="danger"
          @click="exportSalaryDetail()"
          >{{ activeName == "1" ? "明细导出" : "汇总导出" }}</el-button
        >
        <el-tag v-if="activeName == '1'" style="margin-left: 10px"
          >工资合计:{{ craftPrice }}元</el-tag
        >
      </el-row>
    </el-form>
    <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="明细查询" name="1">
        <el-table
          :data="tableData"
          style="width: 100%"
          border
          v-loading="loading"
        >
          >
          <el-table-column label="序号" type="index" align="center">
          </el-table-column>
          <el-table-column
            prop="reportTime"
            label="报工时间"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="wrokId"
            label="工单编号"
            width="180"
            align="center"
          >
          </el-table-column>

          <el-table-column
            prop="reportUserName"
            label="员工名称"
            width="120"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="productName"
            label="产品名称"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="craftName"
            label="工序"
            width="100"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="passNum" label="良品数量" align="center">
          </el-table-column>
          <el-table-column
            prop="noPassNum"
            width="100"
            label="不良品数量"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="craftPriceNum"
            label="计件单价（元）"
            width="115"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="craftPriceTime"
            width="160"
            label="计时单价（元/小时）"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="useTime" label="用时" align="center">
          </el-table-column>
          <el-table-column prop="craftsNames" label="结算方式" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.payProject == 1">计件</el-tag>
              <el-tag v-if="scope.row.payProject == 2">计时</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="total" label="总价" align="center">
          </el-table-column>
          <el-table-column prop="remark" label="报工备注" align="center">
          </el-table-column>
          <el-table-column prop="workRemark" label="工单备注" align="center">
          </el-table-column>
          <el-table-column
            label="操作"
            width="180"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                class="el-icon-edit"
                v-hasPermi="['business:salary:edit']"
                @click="editNum(scope.row)"
                style="margin-right: 20px"
                >修改</el-button
              >
              <el-switch
                v-if="isCheck == 1"
                active-color="#13ce66"
                v-model="scope.row.status"
                active-value="1"
                v-hasPermi="['business:salary:editStatus']"
                inactive-value="0"
                :disabled="scope.row.status == 1"
                @change="handleStatusChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin-top: 10px"
          align="center"
          :hide-on-single-page="false"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 15, 20, 30]"
          :page-size="10"
          :current-page="searchData.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="汇总查询" name="2">
        <el-row>
          <el-table
            :data="summaryTableData"
            style="width: 100%"
            border
            v-loading="loading"
          >
            <el-table-column label="序号" type="index" align="center">
            </el-table-column>
            <el-table-column
              prop="reportUserName"
              label="员工名称"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" align="center">
            </el-table-column>
            <el-table-column prop="craftName" label="工序" align="center">
            </el-table-column>
            <el-table-column prop="totalNum" label="良品数量" align="center">
            </el-table-column>
            <el-table-column
              prop="totalNoNum"
              label="不良品数量"
              align="center"
            >
            </el-table-column>
          </el-table>
        </el-row>
      </el-tab-pane>
      <el-dialog
        title="修改数量"
        :visible.sync="editDialogVisible"
        width="20%"
        :before-close="handleClose"
      >
        <el-form
          ref="elForm"
          :model="editForm"
          size="medium"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="良品数量" prop="passNum">
            <el-input
              v-model="editForm.passNum"
              style="width: 180px"
            ></el-input>
          </el-form-item>
          <el-form-item label="不良品数量">
            <el-input
              v-model="editForm.noPassNum"
              style="width: 180px"
            ></el-input>
          </el-form-item>
          <el-form-item label="用时">
            <el-input
              v-model="editForm.useTime"
              style="width: 180px"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitEditNum">确 定</el-button>
        </span>
      </el-dialog>
    </el-tabs>
  </div>
</template>

<script>
const moment = require("moment");
import {
  getSalaryListApi,
  getSalaryListAllApi,
  salaryEditApi,
  salaryEditStatusApi,
  getAllListUserApi,
} from "@/api/salary/salary.js";
import DatePicker from "../../components/DatePicker/index.vue";
// 定义一个变量，用于跟踪上一次点击的tab的名称
let lastActiveName = null;
export default {
  components: { DatePicker },
  data() {
    return {
      loading: true,
      tableData: [],
      craftPrice: 0, //工资汇总
      summaryTableData: [],
      dataTime: [],
      searchData: {
        startTime: undefined,
        endTime: undefined,
        reportUser: undefined,
        is: "1",
        pageNum: 1, // 当前页
        pageSize: 10, // 每页最大数
      },
      searchDisabled: false,
      allSearchDis: false,
      activeName: "1",
      total: 0,
      userList: [],
      editDialogVisible: false,
      editForm: { passNum: undefined, pkProReportWork: undefined },
      rules: {
        passNum: [{ required: true, message: "请输入数量", trigger: "blur" }],
      },
      isCheck: undefined,
    };
  },
  created() {
    this.initDate();
    // 取vuex中的是否需要审核字段 1需要审核显示否则隐藏
    this.isCheck = this.$store.state.user.isCheck;
    this.getAllListUser();
    this.getSalaryList(1);
  },
  methods: {
    initDate() {
      // 获取当月第一天
      const firstDayOfMonth = moment()
        .startOf("month")
        .format("YYYY-MM-DD HH:mm:ss");
      // 获取当月最后一天
      const lastDayOfMonth = moment()
        .endOf("month")
        .format("YYYY-MM-DD HH:mm:ss");
      this.searchData.startTime = firstDayOfMonth;
      this.searchData.endTime = lastDayOfMonth;
      this.$nextTick(() => {
        this.$refs.DatePicker.startTime = firstDayOfMonth;
        this.$refs.DatePicker.endTime = lastDayOfMonth;
      });
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = "启用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.reportUserName + '"的审核吗？')
        .then(function () {
          return salaryEditStatusApi({ pkProReportWork: row.pkProReportWork });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },

    // 选择日期
    changeTime(e) {
      this.searchData.startTime = moment(e.startTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      // 设置 endTime 为 e.endTime 日期的 23:59:59
      let endTimeMoment = moment(e.endTime); // 确保 e.endTime 是 moment 对象
      endTimeMoment.hours(23).minutes(59).seconds(59); // 设置时间为 23:59:59
      this.searchData.endTime = endTimeMoment.format("YYYY-MM-DD HH:mm:ss"); // 格式化 endTime
      this.searchData.pageNum = 1;
    },

    // 查询所有员工
    async getAllListUser() {
      try {
        const res = await getAllListUserApi();
        this.userList = res;
      } catch (error) {
        console.log(error);
      }
    },

    // 点击tab切换
    handleClick() {
      // 检查当前点击的tab是否与上一次点击的tab相同
      if (this.activeName !== lastActiveName) {
        this.searchData.is = this.activeName;
        // this.searchData.startTime = undefined;
        // this.searchData.endTime = undefined;
        // this.searchData.reportUser = undefined;
        this.getCommonList();
        // 更新上一次点击的tab的名称
        lastActiveName = this.activeName;
      }
    },

    // 查询明细列表
    async getSalaryList(is) {
      try {
        this.loading = true;
        this.searchDisabled = true;
        this.searchData.is = is;
        const res = await getSalaryListApi(this.searchData);
        console.log("查询明细列表", res);
        if (res.proReportWorkPageInfo) {
          this.tableData = res.proReportWorkPageInfo.list;
          this.craftPrice = res.craftPrice;
          this.total = res.proReportWorkPageInfo.total;
        } else {
          this.tableData = [];
          this.craftPrice = 0;
          this.total = 0;
        }
      } catch (error) {
      } finally {
        this.searchDisabled = false;
        this.loading = false;
      }
    },

    // 汇总查询
    async getSalaryAllList(is) {
      this.loading = true;
      try {
        this.allSearchDis = true;
        this.searchData.is = is;
        const res = await getSalaryListAllApi(this.searchData);
        // console.log("汇总查询列表", res);
        this.summaryTableData = res.list;
        this.loading = false;
      } catch (error) {
      } finally {
        this.allSearchDis = false;
      }
    },

    // 获取列表信息
    getCommonList() {
      if (this.activeName == "1") {
        this.getSalaryList(1);
      } else {
        this.getSalaryAllList(2);
      }
    },

    // 导出
    exportSalaryDetail() {
      let text = this.searchData.is == "1" ? "明细导出工资" : "汇总导出工资";
      this.download(
        "/business/reportWork/export",
        {
          ...this.searchData,
        },
        `${text}${new Date().getTime()}.xlsx`
      );
    },

    // 修改数量
    editNum(row) {
      this.editForm = JSON.parse(JSON.stringify(row));
      this.editDialogVisible = true;
    },
    // 保存修改
    async submitEditNum() {
      try {
        const { passNum, noPassNum, useTime, pkProReportWork, pkProWork } =
          this.editForm;
        let params = {
          passNum,
          noPassNum,
          useTime,
          pkProReportWork,
          pkProWork,
        };
        const res = await salaryEditApi(params);
        this.$message.success("修改成功");
        this.getSalaryList(1);
        this.handleClose();
      } catch (error) {
        this.$message.error("修改失败");
      }
    },

    // getSummaries(param) {
    //   console.log("craftPrice", this.craftPrice);
    //   const { columns, data } = param;
    //   const sums = [];
    //   columns.forEach((column, index) => {
    //     if (index === 0) {
    //       sums[index] = "合计";
    //       return;
    //     }
    //     if (index === 11) {
    //       //指定哪一列合计（从0开始计数） 如果需要全部合计 去掉这个判断即可
    //       const values = data.map((item) => Number(item[column.property]));
    //       if (!values.every((value) => isNaN(value))) {
    //         sums[index] = values.reduce((prev, curr) => {
    //           console.log();
    //           const value = Number(curr);
    //           if (!isNaN(value)) {
    //             return prev + curr;
    //           } else {
    //             return prev;
    //           }
    //         }, 0);
    //       } else {
    //         sums[index] = "";
    //       }
    //     }
    //   });
    //   return sums;
    // },

    // 使用后端合计
    getSummaries(param) {
      const { columns } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index === 11) {
          const craftPrice = this.craftPrice; // 后端返回的值
          sums[index] = craftPrice;
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },

    // 关闭弹窗
    handleClose() {
      this.editForm.passNum = undefined;
      this.editForm.pkProReportWork = undefined;
      this.editForm.noPassNum = undefined;
      this.editForm.useTime = undefined;
      this.editDialogVisible = false;
    },
    //分页修改每页显示条数
    handleSizeChange(val) {
      this.searchData.pageSize = val;
      this.getSalaryList(1);
    },
    //分页跳转页面
    handleCurrentChange(val) {
      this.searchData.pageNum = val;
      this.getSalaryList(1);
    },
  },
};
</script>

<style>
.row-bg {
  padding: 10px 0;
}
.popover-content {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 3px;
}
.el-button--mini.is-circle {
  padding: 2px !important;
}
.container {
  overflow-x: auto;
}
</style>
